package cn.itsource.service.impl;

import cn.itsource.config.anno.MyLog;
import cn.itsource.domain.BlogFriendAddress;
import cn.itsource.mapper.FriendAddressMapper;
import cn.itsource.query.BlogFriendAddressQuery;
import cn.itsource.service.BlogFriendAddressService;
import cn.itsource.util.UserTools;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;
import java.util.List;

/**
 * 实现业务层的接口
 */
@Service
public class BlogFriendAddressServiceimpl implements BlogFriendAddressService {

//    注入mapper层
    @Autowired
    private FriendAddressMapper mapper;


    @Override
    @MyLog(value = "友情链接")
    public BlogFriendAddress findOne(Long id) {
        return mapper.selectByPrimaryKey(id);
    }

    @Override
    public List<BlogFriendAddress> findAll() {
        //使用tk的方法查询全部
        return mapper.selectAll();
    }

    @Override
    @MyLog(value = "友情链接")
    public void saveOrUpdate(BlogFriendAddress friendAddress) {
//        修改时间
        friendAddress.setUpdateTime(new Date());
//        修改人姓名
        friendAddress.setUpdateUserName(UserTools.getCurrentUserRealName());
        try {
            if (friendAddress.getId() == null) {
                mapper.insertSelective(friendAddress);
            } else {
                mapper.updateByPrimaryKey(friendAddress);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
//        使用tk的方法添加


    }

    @Override
    @MyLog(value = "友情链接",isImportant = true)
    public void delete(Long id) {
        //        使用tk的方法删除
        mapper.deleteByPrimaryKey(id);

    }



    @Override
    public PageInfo<BlogFriendAddress> pageList(BlogFriendAddressQuery query) {
        PageHelper.startPage(query.getPage(),query.getRows());
        //高级查询，封装查询条件 参数：查询的domain的class类型
        Example example = new Example(BlogFriendAddress.class);
        //判断keyword是有效值
        if (StringUtils.isNotBlank(query.getKeyword())){
            example.and().andLike("name","%"+query.getKeyword()+"%");
            example.or().orLike("address","%"+query.getKeyword()+"%");
        }

        List<BlogFriendAddress> blogFriendAddresses = mapper.selectByExample(example);
        //封装成pageInfo
        PageInfo<BlogFriendAddress> pageInfo = new PageInfo<>(blogFriendAddresses);
        //返回数据
        return pageInfo;
    }


}
